<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-4">
      <h1 class="text-2xl font-bold text-gray-800">试卷向导</h1>
      <router-link to="/" class="text-blue-600">返回仪表盘</router-link>
    </div>

    <div class="bg-white rounded shadow p-4">
      <div class="flex gap-2 mb-4">
        <button class="px-3 py-2 border rounded" :class="step===1?'bg-gray-100':''" @click="step=1">1. 选择题目</button>
        <button class="px-3 py-2 border rounded" :class="step===2?'bg-gray-100':''" @click="step=2">2. 预览</button>
        <button class="px-3 py-2 border rounded" :class="step===3?'bg-gray-100':''" @click="step=3">3. 创建</button>
      </div>

      <div v-if="step===1" class="grid md:grid-cols-3 gap-4">
        <div>
          <div class="font-semibold mb-2">问题库</div>
          <div class="space-y-2 max-h-80 overflow-auto border rounded p-2">
            <label v-for="i in issues" :key="i.id" class="flex items-center gap-2 text-sm">
              <input type="checkbox" :value="i.id" v-model="selectedIssues"> #{{ i.id }} {{ i.title }}
            </label>
          </div>
        </div>
        <div>
          <div class="font-semibold mb-2">知识库</div>
          <div class="space-y-2 max-h-80 overflow-auto border rounded p-2">
            <label v-for="k in knowledge" :key="k.id" class="flex items-center gap-2 text-sm">
              <input type="checkbox" :value="k.id" v-model="selectedKnowledge"> #{{ k.id }} {{ k.title }}
            </label>
          </div>
        </div>
        <div>
          <div class="font-semibold mb-2">复盘</div>
          <div class="space-y-2 max-h-80 overflow-auto border rounded p-2">
            <label v-for="r in reviews" :key="r.id" class="flex items-center gap-2 text-sm">
              <input type="checkbox" :value="r.id" v-model="selectedReviews"> #{{ r.id }} {{ r.root_cause || '复盘条目' }}
            </label>
          </div>
        </div>
        <div class="md:col-span-3 flex justify-end mt-2">
          <button class="px-4 py-2 bg-blue-600 text-white rounded" @click="step=2">下一步</button>
        </div>
      </div>

      <div v-else-if="step===2" class="space-y-3">
        <div class="text-sm text-gray-600">标题</div>
        <input v-model="title" class="border rounded px-3 py-2 w-full" placeholder="请输入试卷标题" />
        <div class="grid md:grid-cols-2 gap-4">
          <div>
            <div class="font-semibold mb-2">预览 - 问题 ({{ selectedIssues.length }})</div>
            <ul class="list-disc pl-5 text-sm">
              <li v-for="id in selectedIssues" :key="'i'+id">#{{ id }} {{ issuesMap.get(id)?.title }}</li>
            </ul>
          </div>
          <div>
            <div class="font-semibold mb-2">预览 - 知识 ({{ selectedKnowledge.length }})</div>
            <ul class="list-disc pl-5 text-sm">
              <li v-for="id in selectedKnowledge" :key="'k'+id">#{{ id }} {{ knowledgeMap.get(id)?.title }}</li>
            </ul>
          </div>
          <div>
            <div class="font-semibold mb-2">预览 - 复盘 ({{ selectedReviews.length }})</div>
            <ul class="list-disc pl-5 text-sm">
              <li v-for="id in selectedReviews" :key="'r'+id">#{{ id }} {{ reviewsMap.get(id)?.root_cause || '复盘条目' }}</li>
            </ul>
          </div>
        </div>
        <div class="flex justify-between mt-2">
          <button class="px-4 py-2 border rounded" @click="step=1">上一步</button>
          <button class="px-4 py-2 bg-blue-600 text-white rounded" @click="step=3">继续</button>
        </div>
      </div>

      <div v-else class="space-y-3">
        <div class="text-gray-700">确认创建该试卷？</div>
        <div class="flex justify-between">
          <button class="px-4 py-2 border rounded" @click="step=2">返回</button>
          <button class="px-4 py-2 bg-green-600 text-white rounded disabled:opacity-60" :disabled="!title || creating" @click="createExam">{{ creating ? '创建中...' : '创建' }}</button>
        </div>
      </div>
    </div>

    <div v-if="createdExam" class="mt-4 bg-green-50 border border-green-200 rounded p-3 text-green-800">
      已创建试卷：#{{ createdExam.id }} {{ createdExam.title }}
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import api from '../api'

const step = ref(1)
const title = ref('')

const issues = ref([])
const knowledge = ref([])
const reviews = ref([])

const selectedIssues = ref([])
const selectedKnowledge = ref([])
const selectedReviews = ref([])

const issuesMap = computed(() => new Map(issues.value.map(i => [i.id, i])))
const knowledgeMap = computed(() => new Map(knowledge.value.map(k => [k.id, k])))
const reviewsMap = computed(() => new Map(reviews.value.map(r => [r.id, r])))

const createdExam = ref(null)
const creating = ref(false)

onMounted(async () => {
  const [ir, kr, rr] = await Promise.all([
    api.get('/api/issues'),
    api.get('/api/knowledge'),
    api.get('/api/reviews')
  ])
  issues.value = ir.data || []
  knowledge.value = kr.data || []
  reviews.value = rr.data || []
})

const createExam = async () => {
  if (!title.value) { alert('请输入试卷标题'); return }
  if (
    (!selectedIssues.value || selectedIssues.value.length === 0) &&
    (!selectedKnowledge.value || selectedKnowledge.value.length === 0) &&
    (!selectedReviews.value || selectedReviews.value.length === 0)
  ) {
    if (!confirm('未选择任何条目，确定仍然创建空试卷吗？')) return
  }
  creating.value = true
  try {
    const res = await api.post('/api/exams', {
      title: title.value,
      issue_ids: selectedIssues.value,
      knowledge_ids: selectedKnowledge.value,
      review_ids: selectedReviews.value,
    })
    createdExam.value = res.data
    step.value = 1
    title.value = ''
    selectedIssues.value = []
    selectedKnowledge.value = []
    selectedReviews.value = []
    alert('试卷创建成功')
  } catch (e) {
    alert(e?.response?.data?.detail || '创建失败，请稍后重试')
  } finally {
    creating.value = false
  }
}
</script>

<style>
@import "https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css";
</style>
